using System;
using System.Collections.Generic;
using System.Text;

namespace OurMediaPlayer.Logic.Filters
{
    class DiferencasFilter: Filter
    {
        public DiferencasFilter()
        { 
        
        }

        public override void Process(byte[] source, IntPtr destination, MediaInfo videoInfo)
        {
            unsafe
            {
                fixed (byte* pSource = (byte*)&source[0])
                {
                    byte* d = (byte*)(void*)destination;
                    byte* s = pSource;

                    int stride = videoInfo.MediaStride;
                    int stride2 = videoInfo.MediaStride * 2;

                    int width, height;
                    if (this.Complete)
                    { 
                        width = videoInfo.MediaWidth;
                        height = videoInfo.MediaHeight;
                    }
                    else
                    {
                        width = Math.Abs(this.Xmax - this.Xmin);
                        height = Math.Abs(this.Ymax - this.Ymin);

                        int ymin = Math.Min(this.Ymax, this.Ymin);
                        int xmin = Math.Min(this.Xmax, this.Xmin);

                        d += ymin * stride + xmin * 3;
                        s += ymin * stride + xmin * 3;
                    }

                    int nOffset = videoInfo.MediaStride - width * 3;
                    int nWidth = width * 3;

                    int nPixel = 0, nPixelMax = 0;

                    for (int y = 0; y < height - 2; ++y)
                    {
                        for (int x = 0; x < nWidth - 2; ++x)
                        {
                            nPixelMax = Math.Abs((s)[0] - (s + stride2 + 6)[0]);
                            nPixel = Math.Abs((s + 6)[0] - (s + stride2 - 6)[0]);
                            if (nPixel > nPixelMax) nPixelMax = nPixel;

                            nPixel = Math.Abs((s + 3)[0] - (s + stride2 + 3)[0]);
                            if (nPixel > nPixelMax) nPixelMax = nPixel;

                            nPixel = Math.Abs((s + stride)[0] - (s + stride + 6)[0]);
                            if (nPixel > nPixelMax) nPixelMax = nPixel;

                            if (nPixelMax < 127) nPixelMax = 0;

                            d[0] = (byte)nPixelMax;

                            ++d;
                            ++s;
                        }


                        d += 2 + nOffset;
                        s += 2 + nOffset;
                    }
                }
            }
        }
    }
}
